from django.core.cache import cache
from typing import Any, Optional
import logging

logger = logging.getLogger('apps')

class CacheManager:
    @staticmethod
    def get_key(prefix: str, *args) -> str:
        """生成缓存键"""
        key = f"{prefix}_{'_'.join(map(str, args))}"
        logger.debug(f"生成缓存键: {key}")
        return key

    @staticmethod
    def set(key: str, value: Any, timeout: int = 3600) -> bool:
        """设置缓存"""
        try:
            logger.debug(f"设置缓存: {key}, timeout: {timeout}")
            cache.set(key, value, timeout)
            return True
        except Exception as e:
            logger.error(f"设置缓存失败: {key}, error: {str(e)}")
            return False

    @staticmethod
    def get(key: str, default: Any = None) -> Optional[Any]:
        """获取缓存"""
        try:
            value = cache.get(key, default)
            logger.debug(f"获取缓存: {key}, 是否命中: {value is not None}")
            return value
        except Exception as e:
            logger.error(f"获取缓存失败: {key}, error: {str(e)}")
            return default

    @staticmethod
    def delete(key: str) -> bool:
        """删除缓存"""
        try:
            logger.debug(f"删除缓存: {key}")
            cache.delete(key)
            return True
        except Exception as e:
            logger.error(f"删除缓存失败: {key}, error: {str(e)}")
            return False 